//
//  CNKISqlTools.m
//  CNKICommunity
//
//  Created by wei on 17/3/6.
//  Copyright © 2017年 CNKI. All rights reserved.
//

#import "CNKISqlTools.h"

#import "CNKIProfessionalModel.h"
#import <sqlite3.h>


@implementation CNKISqlTools

static sqlite3 *_db;

//创建数据库
+(void)initialize
{
    //获取数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];
    NSString *fileName = [doc stringByAppendingPathComponent:@"Professional.sqlite"];
    //oc转换为c
    const char *cfileName = fileName.UTF8String;
    //打开数据库
    int result = sqlite3_open(cfileName, &_db);
    if (result == SQLITE_OK)
    {
        NSLog(@"成功打开数据库");
        //创建表
        const char *sql = "CREATE TABLE IF NOT EXISTS t_person (id integer PRIMARY KEY AUTOINCREMENT,name text NOT NULL);";
        
        char *errmsg = NULL;
        result = sqlite3_exec(_db, sql, NULL, NULL, &errmsg);
        if (result == SQLITE_OK)
        {
            NSLog(@"创表成功");
        }else
        {
            printf("创表失败---%s",errmsg);
        }
        
    }else
    {
        NSLog(@"打开数据库失败");
    }
    
}
+(void)save:(CNKIProfessionalModel *)model
{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_person (name) VALUES ('%@');",model.ProfessionalName];
    char *errmsg = NULL;
    sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errmsg);
    if (errmsg)
    {
        NSLog(@"插入数据失败");
    }else
    {
        NSLog(@"插入数据成功");
    }
}
+(NSArray *)queryWithCondition:(NSString *)condition
{
    NSMutableArray *professionalArr = nil;
    NSString *NSsql = [NSString stringWithFormat:@"SELECT id,name FROM t_person WHERE name like '%%%@%%';",condition];
    NSLog(@"%@",NSsql);
    const char *sql = NSsql.UTF8String;
    sqlite3_stmt *stmt = NULL;
    
    //进入查询前的准备工作
    if (sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL)==SQLITE_OK)
    {
        professionalArr = [NSMutableArray array];
        //每调用一次sqlite3_step函数，atmt就会指向下一条记录
        while (sqlite3_step(stmt) == SQLITE_ROW)
        {
            const unsigned char *name = sqlite3_column_text(stmt, 1);
            CNKIProfessionalModel *model = [CNKIProfessionalModel new];
            model.ProfessionalName = [NSString stringWithUTF8String:(const char *)name];
            [professionalArr addObject:model];
        }
    }else
    {
        NSLog(@"查询有问题");
    }
    
    return professionalArr;
}
@end
